package net.dgg.zz.credential.qualificationTransfer.controller;

import net.dgg.framework.tac.utils.bean.DggRestResponse;
import net.dgg.framework.tac.utils.web.commmon.DggBaseController;
import net.dgg.iboss.base.util.datatable.DataTableUtils;
import net.dgg.iboss.base.util.datatable.domain.DataTableRequest;
import net.dgg.tmd.foundation.platform.annotation.AuthOpt;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.DataTableResponse;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.common.utils.excel.ExcelUtils;
import net.dgg.zz.credential.qualificationTransfer.entity.QualificationTransferRecord;
import net.dgg.zz.credential.qualificationTransfer.entity.QualificationTransferVo;
import net.dgg.zz.credential.qualificationTransfer.entity.ReviewRejectedVo;
import net.dgg.zz.credential.qualificationTransfer.service.QualificationTransferService;
import net.dgg.zz.credential.warningConfigure.constant.WarningType;
import net.dgg.zz.credential.warningConfigure.service.SystemConfigureService;
import net.fblock.log.NLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 资质转让审核
 */
@Controller
@RequestMapping("/zs/credential/qualification_transfer")
public class QualificationTransferController extends DggBaseController {


    @Autowired
    private CommonService commonService;
    @Autowired
    private QualificationTransferService qualificationTransferService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private SystemConfigureService configureService;
    @Autowired
    private SystemRecordService systemRecordService;

    /*
     * @Author zsx
     * @Date 2018-08-30 08:08:33
     * @Description   初始化资质转让审核
     * @return String
     */
    @RequestMapping("/index")
    @AuthOpt(code = "ZZ_TRANSFER_AUDIT")
    public String index(Model model) {
        model.addAttribute("generalType", CredentialConstant.ZZ_CREDENTIAL);
        // 适用范围
        List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
        model.addAttribute("applicationScopes", applicationScopes);
        //超期状态
        List<Map> overdueStatus = commonService.queryTreeBook(CredentialConstant.CERTIFICATE_APTITUDE_EXCEED, 1, 2, null);
        model.addAttribute("overdueStatus", overdueStatus);
        model.addAttribute("currentAuditerId", sessionManager.getCurrentUser().getId());
        getAptitudeLevels(model);
        return "zzsc/credential/qualificationTransfer/index";
    }

    /*
     * @Author zsx
     * @Date 2018-08-30 08:08:26
     * @Description  分页获取待审核数据
     * @param params
     * @return DataTableResponse
     */
    @RequestMapping("/get_pending_audit")
    @ResponseBody
    public DataTableResponse getPendingAudit(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        try {
            DataTableRequest dt = DataTableUtils.getParam(request);
            params.put("page", dt.getPage());
            params.put("limit", dt.getLength());
            List<QualificationTransferVo> list = qualificationTransferService.queryPendingAuditWithPage(params);
            return new DataTableResponse().data(params, list);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new DataTableResponse().data(params, null);
        }
    }

    /*
     * @Author zsx
     * @Date 2018-08-30 02:08:47
     * @Description  初始化审核界面
     * @param id 资质转让id
     * @return String
     */
    @RequestMapping("/audit_index")
    public String auditIndex(@RequestParam Long id, Model model) {
        Map<String, Object> restMap = qualificationTransferService.selectTransferDetails(id);
        model.addAttribute("restMap", restMap);
        List<Map> auditStatus = commonService.queryTreeBook(CredentialConstant.TRANSFER_AUDIT_STATUS, 1, 2, null);
        //移除待审核状态
        for (Iterator it = auditStatus.iterator(); it.hasNext(); ) {
            Map str = (Map) it.next();
            if (str.get("code").equals(CredentialConstant.TRANSFER_CHECK_PENDING)) {
                it.remove();
            }
        }
        model.addAttribute("auditStatus", auditStatus);
        model.addAttribute("rejectedAudit", CredentialConstant.TRANSFER_REJECTED_AUDIT);
        return "zzsc/credential/qualificationTransfer/audit";
    }

    /*
     * @Author zsx
     * @Date 2018-08-30 08:08:08
     * @Description 资质审核
     * @param params
     * @return DggRestResponse
     */
    @RequestMapping("/audit_qualification")
    @ResponseBody
    @NLog
    public DggRestResponse auditQualification(@RequestParam Map<String, Object> params) {
        try {
            if (StringUtils.isEmpty(params.get("auditStatus"))) {
                return this.getFailResponse("审核结果不能为空");
            }
            Map<String, Object> map = qualificationTransferService.updateAuditStatus(params);
            if ((Boolean) map.get("status")) {
                return this.getSuccessResponse("");
            } else {
                return this.getFailResponse(map.get("msg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("服务器错误，请联系管理员");
        }
    }

    /*
     * @Author zsx
     * @Date 2018-08-30 02:08:49
     * @Description 变更审核人界面初始化
     * @param id 资质转让id
     * @return String
     */
    @RequestMapping("/change_auditor")
    @NLog
    public String changeAuditor(Long id, Model model) {
        Map<String, Object> restMap = qualificationTransferService.selectTransferDetails(id);
        model.addAttribute("restMap", restMap);
        return "zzsc/credential/qualificationTransfer/change";
    }

    /*
     * @Author zsx
     * @Date 2018-08-30 04:08:59
     * @Description 修改资质审核人
     * @param id 资质转让id
     * @param nextReviewer 审核人
     * @param remark 备注
     * @return DggRestResponse
     */
    @RequestMapping("/update_auditor")
    @ResponseBody
    @NLog
    public DggRestResponse updateAuditor(Long id, Long nextReviewer, String remark) {
        try {
            Map<String, Object> map = qualificationTransferService.updateAuditor(id, nextReviewer, remark == null ? "" : remark);
            if ((Boolean) map.get("status")) {
                return this.getSuccessResponse("");
            } else {
                return this.getFailResponse(map.get("msg").toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return this.getFailResponse("服务器错误,请联系管理员");
        }
    }


    /*
     * @Author zsx
     * @Date 2018-08-30 01:08:27
     * @Description 审核设置界面初始化
     */
    @RequestMapping("/setting_index")
    public String settingIndex(Model model) {
        Map<String, Object> params = new HashMap<>();
        params.put("signOrgId", commonService.findUserSyb(sessionManager.getCurrentUser()));
        params.put("warningType", CredentialConstant.ZZ_CREDENTIAL);
        params.put("warningName", WarningType.REVIEW_PROGRESSION);
        Map<String, Object> map = configureService.querySingleWarning(params);
        model.addAttribute("reviewSeries", 2);
        if ((Boolean) map.get("status")) {
            if (map.containsKey("configValue") && null != map.get("configValue")) {
                model.addAttribute("reviewSeries", map.get("configValue"));
            }
        }
        return "zzsc/credential/qualificationTransfer/setting";
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 02:08:26
     * @Description 初始化资质转让驳回记录
     * @return string
     */
    @RequestMapping("/rejected_record")
    @AuthOpt(code = "ZZ_REJECTED_RECORD")
    public String rejectedRecord(Model model) {
        model.addAttribute("generalType", CredentialConstant.ZZ_CREDENTIAL);
        // 适用范围
        List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
        model.addAttribute("applicationScopes", applicationScopes);
        getAptitudeLevels(model);
        return "zzsc/credential/qualificationTransfer/rejected_record";
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 02:08:26
     * @Description 初始化已转让资质记录
     * @return string
     */
    @RequestMapping("/transferred_record")
    @AuthOpt(code = "ZZ_TRANSFERRED_RECORD")
    public String transferredRecord(Model model) {
        model.addAttribute("generalType", CredentialConstant.ZZ_CREDENTIAL);
        // 适用范围
        List<Map> applicationScopes = commonService.queryTreeBook(CredentialConstant.CREDENTIAL_APPLICATION_SCOPE, 1, 2, null);
        model.addAttribute("applicationScopes", applicationScopes);
        getAptitudeLevels(model);
        return "zzsc/credential/qualificationTransfer/transferred_record";
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 02:08:50
     * @Description 分页查询资质驳回记录
     * @param params
     * @return DataTableResponse
     */
    @RequestMapping("/get_rejected_record")
    @ResponseBody
    @NLog
    public DataTableResponse getRejectedRecord(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        try {
            DataTableRequest dt = DataTableUtils.getParam(request);
            params.put("page", dt.getPage());
            params.put("limit", dt.getLength());
            List<QualificationTransferVo> transferVos = qualificationTransferService.queryRejectedRecordWithPage(params);
            return new DataTableResponse().data(params, transferVos);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new DataTableResponse().data(params, null);
        }
    }


    /*
     * @Author zsx
     * @Date 2018-08-31 02:08:51
     * @Description 分页查询已转让资质记录
     * @param params
     * @return DataTableResponse
     */
    @RequestMapping("/get_transferred_record")
    @ResponseBody
    @NLog
    public DataTableResponse getTransferredRecord(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        try {
            DataTableRequest dt = DataTableUtils.getParam(request);
            params.put("page", dt.getPage());
            params.put("limit", dt.getLength());
            List<QualificationTransferVo> transferVos = qualificationTransferService.queryTransferredRecordithPage(params);
            return new DataTableResponse().data(params, transferVos);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new DataTableResponse().data(params, null);
        }
    }

    /*
     * @Author zsx
     * @Date 2018-08-31 06:08:30
     * @Description 导出资质审核驳回记录
     * @return void
     */
    @RequestMapping("/export_rejected_record")
    @NLog
    public void exportRejectedRecord(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        try {
            List<ReviewRejectedVo> rejectedVos = qualificationTransferService.selectRejectedRecord(params);
            for (ReviewRejectedVo dto:rejectedVos){
                dto.setCertificateArea((dto.getAreaProvince()==null?"":dto.getAreaProvince())+"/"+(dto.getCertificateArea()==null?"":dto.getCertificateArea()));
                dto.setExpiryTime(DateUtils.dateString(dto.getCertificateExpiryTime(),DateUtils.yyyy_MM_dd));
            }
            String fileName = "资质转让驳回记录" + DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss) + ".xlsx";
            ExcelUtils.writeToFile(rejectedVos, null, fileName, response,ReviewRejectedVo.class);
            //日志
            SystemRecord record = new SystemRecord();
            record.setSource("1");
            record.setOperateType("53");
            record.setWorkTableName("zz_qualification_transfer");
            record.setRemarks("导出资质审核驳回记录");
            systemRecordService.save(record);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    /*
     * @Author zsx
     * @Date 2018-08-31 06:08:30
     * @Description 导出资质审核通过记录
     * @return void
     */
    @RequestMapping("/export_transferred_record")
    @NLog
    public void exportTransferredRecord(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        try {
            List<QualificationTransferVo> transferVos = qualificationTransferService.selectTransferredRecord(params);
            for (QualificationTransferVo dto:transferVos){
                dto.setCertificateArea((dto.getAreaProvince()==null?"":dto.getAreaProvince())+"/"+(dto.getCertificateArea()==null?"":dto.getCertificateArea()));
                dto.setExpiryTime(DateUtils.dateString(dto.getCertificateExpiryTime(),DateUtils.yyyy_MM_dd));
            }
            String fileName = "已转让资质记录" + DateUtils.dateString(new Date(), DateUtils.yyyy_MM_dd_HH_mm_ss) + ".xlsx";
            ExcelUtils.writeToFile(transferVos, null, fileName, response,QualificationTransferVo.class);
            //日志
            SystemRecord record = new SystemRecord();
            record.setSource("1");
            record.setOperateType("53");
            record.setWorkTableName("zz_qualification_transfer");
            record.setRemarks("导出资质审核通过记录");
            systemRecordService.save(record);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /*
     * @Author zsx
     * @Date 2018-09-04 10:09:18
     * @Description 获取资质等级
     */
    public void getAptitudeLevels(Model model) {
        //资质等级
        List<Map> certificateLevels = commonService.queryTreeBook(CredentialConstant.QUALIFICATION_LEVEL, 1, 2, null);
        model.addAttribute("certificateLevels", certificateLevels);
    }

    /*
     * @Author zsx
     * @Date 2018-09-06 06:09:55
     * @Description 查询记录详情
     * @param transferId 资质转让id
     * @return String
     */
    @RequestMapping("/get_record_details")
    public String recordDetails(@RequestParam Long transferId, Model model) {
        Map<String, Object> restMap = qualificationTransferService.selectTransferDetails(transferId);
        model.addAttribute("restMap", restMap);
        List<QualificationTransferRecord> transferRecords = qualificationTransferService.findRecordDetails(transferId);
        model.addAttribute("transferRecords", transferRecords);
        return "zzsc/credential/qualificationTransfer/record_details";
    }


}
